import axios from "axios";
import router from "@/router";

axios.defaults.baseURL = "http://localhost:8090/";

axios.interceptors.request.use(config => {
    // config.headers["token"] = localStorage.getItem("login-user")
    const user = JSON.parse(localStorage.getItem("login-user")||'{}')
    config.headers.token = user.token //设置请求头

   /* config.headers.token = JSON.parse(localStorage.getItem("login-user")).token*/
    return config

},error=>{
    console.error('request error:'+ error)
    return Promise.reject(error)
});

axios.interceptors.response.use(
    response => {
       /*if (response.config.url.includes('restapi.amap.com')){
           const amapResponse = response.data;
           const status = amapResponse.status;
           const info = amapResponse.info;
           const geocodes = amapResponse.geocodes;

           let res = {
               code: status === '1' ? '200' : '400',
               msg: info,
               data: null
           };

           if (status === '1' && geocodes && geocodes.length > 0) {
               res.data = geocodes[0];
           }

           return res;
       }else {*/

           let res = response.data;

           //兼容服务端返回的字符串数据
           if (typeof res === 'string') {
               res = res ? JSON.parse(res) : res;
           }
           if (res.code === '401') {
               router.push('/')
               setTimeout(() => {
                   localStorage.clear();
                   location.reload();
               }, 1000)
           }
           return res

}, error => {
        //console.error(error.response?.data)
        return Promise.reject(error)
    }
)





export default axios;

